<script setup lang="ts">
import { reactive, ref, onUnmounted } from "vue";
import { Router } from "@/utils/router";
import EditAreaPicker from "@/components/popup/edit-area-picker.vue";
import { onLoad } from "@dcloudio/uni-app";
import { Toast } from "@/utils/toast";
import { upload_up } from "@/api/upload";
import { upload_voice } from "../api/index";
import { throttle } from "@/utils/throttle";
import { chooseMedia } from "@/utils/meida";
import LineItem from "./components/line.vue";
const recorderManager: any = uni.getRecorderManager();
const innerAudioContext: any = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
const editAreaPicker = ref<InstanceType<typeof EditAreaPicker>>();
const editData = reactive({
  title: "", //讲解主题
  desc: "", //讲解描述
  scenic_name: "", //讲解景区
  pic_url: "", //封面图
  content: "", //讲解内容
  audio_url: "", //讲解音频
  audio_time: "", //时间上传音频返回的时间
  city_id: 0, //城市
});
const city_name = ref("");
const inputLength = ref(0);
const handleInput = (event: any) => {
  // 计算输入的字符数
  inputLength.value = event.target.value.length;
};
const inputLength2 = ref(0);
const handleInput2 = (event: any) => {
  // 计算输入的字符数
  inputLength.value = event.target.value.length;
};

const activeIndex = ref(0);
const voiceState = ref(false);
const startRecordVoice = () => {
  uni.getSetting({
    success(res) {
      if (!res.authSetting["scope.writePhotosAlbum"]) {
        // 授权状态为未授权或已拒绝
        // 可以在这里直接调用uni.authorize重新发起授权请求
        uni.authorize({
          scope: "scope.record", // 请替换为需要的权限名
          success() {
            activeIndex.value = 1;
            voiceState.value = true;
            startRecord();
          },
          fail() {
            // 用户拒绝授权
            uni.showModal({
              title: "提示",
              content: "此功能需要授权才能使用，请检查设置",
              success: function (modalRes) {
                if (modalRes.confirm) {
                  // 引导用户去设置中开启权限
                  uni.openSetting();
                }
              },
            });
          },
        });
      }
    },
  });
};
const handleVoice = () => {
  if (voiceState.value) {
    pause();
    closeVoiceLine();
  } else {
    resume();
    startVoiceLine();
  }
  voiceState.value = !voiceState.value;
};
const handleVoice2 = () => {
  voiceState.value = !voiceState.value;
};
const areaClick = () => {
  editAreaPicker.value?.show((area: any, id: number) => {
    city_name.value = area;
    editData.city_id = id;
  });
};
const startRecord = () => {
  recorderManager.start({ format: "mp3" });
  countTimeStart();
};
const endRecord = () => {
  closeVoiceLine();
  recorderManager.stop();
  voiceState.value = false;
  activeIndex.value = 2;
  countTimeEnd2();
};
const pause = () => {
  recorderManager.pause();
  voiceState.value = true;
  countTimeEnd();
};
const resume = () => {
  recorderManager.resume();
  voiceState.value = false;
  countTimeStart();
};

const voicePath = ref("");
const duration = ref(0);
const reLoadVoice = () => {
  recorderManager.stop();
  countTimeEnd2();
  setTimeout(() => {
    startRecordVoice();
  }, 100);
};
const reLoadVoice2 = () => {
  recorderManager.stop();
  activeIndex.value = 0;
  countTimeEnd2();
  clearProgressTime();
};
onLoad(() => {
  // uni.authorize({
  //   scope: "scope.record",
  //   success() {},
  //   fail() {
  //     Toast.show("请授权录音权限");
  //   },
  // });
  // 用户拒绝授权
  // 检查授权状态

  recorderManager.onStop(function (res: any) {
    voicePath.value = res.tempFilePath;
    duration.value = res.duration;
    progress.allTime = msToTime(duration.value);
    getAllTime();
    Toast.show("结束录音");
  });
  recorderManager.onStart(function (res: any) {
    voicePath.value = res;
    Toast.show("开始录音");
  });
});
const playVoice = () => {
  innerAudioContext.src = voicePath.value;
  innerAudioContext.onEnded(() => {
    voiceState.value = false;
    countTimeEnd2();
    clearProgressTime();
  });
  if (voiceState.value) {
    innerAudioContext.pause();
    voiceState.value = false;
    countTimeEnd();
    progressEnd();
  } else {
    if (voicePath.value) {
      voiceState.value = true;
      innerAudioContext.play();
      countTimeStart();
      progressStart();
    }
  }
};
//计时器-----------------------------------------------------------------------
const dateCount = reactive({
  time: "00:00",
  nowDate: 0,
  preCount: 0,
  timer: 0,
});
const interid = ref(0);
const nowDate = ref(0);
const countTimeStart = () => {
  dateCount.nowDate = Date.now();
  interid.value = setInterval(() => {
    const Date1 = Date.now() - dateCount.nowDate + dateCount.preCount;
    dateCount.timer = Date1;
    dateCount.time = msToTime(Date1);
  }, 1000);
};
const countTimeEnd = () => {
  dateCount.preCount = dateCount.timer;
  clearInterval(interid.value);
};
const countTimeEnd2 = () => {
  clearInterval(interid.value);
  resetTime();
};
const resetTime = () => {
  dateCount.time = "00:00";
  dateCount.nowDate = 0;
  dateCount.preCount = 0;
  dateCount.timer = 0;
};
//计时器-----------------------------------------------------------------------

//播放时间-------------------------------------------------------------------------
const setProgress = () => {
  duration.value;
};
const progress = reactive({
  allTime: "00:00",
});

const msToTime = (milliseconds: any) => {
  // 初始化变量
  let seconds: any = Math.floor((milliseconds / 1000) % 60);
  let minutes: any = Math.floor((milliseconds / (1000 * 60)) % 60);
  let hours: any = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);

  // 保证每个部分都是两位数
  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  // 返回格式化的时间字符串
  return minutes + ":" + seconds;
};
//播放时间-------------------------------------------------------------------------

//进度条 -------------------------------------------------------------
const playTime = ref(0);
const allTime = ref(0);
const allTimeShow = ref("");
const preWidth = ref(0);
const width = ref("0%");
const progressInterId = ref(0);
// 当你需要获取播放时长时
const getPlayDuration = () => {
  const currentTime = Date.now();
  // 当前时间减去开始播放时的时间就是播放的时长（单位：毫秒）
  const duration = currentTime - playTime.value;
  // 如果需要转换成秒，可以除以1000
  const durationInSeconds = duration / 1000;
  return durationInSeconds;
};
const getAllTime = () => {
  const [minute, second] = progress.allTime.split(":");
  allTime.value = Number(minute) * 60 + Number(second);
};
const inter = () => {
  const playNow = getPlayDuration();
  const time = (playNow / allTime.value) * 100;
  const time2 = time.toFixed(2);
  const time3 = preWidth.value + Number(time2);
  width.value = time3 + "%";
};
const progressStart = () => {
  playTime.value = Date.now();
  progressInterId.value = setInterval(() => {
    inter();
  }, 100);
};
const progressEnd = () => {
  preWidth.value = Number(width.value.split("%")[0]);
  clearInterval(progressInterId.value);
};
const clearProgressTime = () => {
  width.value = "0%";
  preWidth.value = 0;
  clearInterval(progressInterId.value);
};

//进度条-------------------------------------------------------------

//上传文件，添加音频----------------------------------------------------------------------------------------
const uploadImg = (url: string, type: number) => {
  return upload_up(url, { type }).then((res: any) => {
    return res[0].url;
  });
};
const toRequire2 = () => {
  throttle(toRequire, 1000);
};
const toRequire = async () => {
  if (!voicePath.value) {
    return Toast.show("请录制音频");
  }
  const url = await uploadImg(voicePath.value, 5);
  editData.audio_url = url;
  editData.audio_time = progress.allTime;
  Toast.showLoading();
  if (editData.audio_url) {
    upload_voice(editData)
      .then(() => {
        Router.navigateTo(`/package/voice/pages/apply/index`);
        Toast.hideLoading();
      })
      .catch(() => {
        Toast.hideLoading();
      });
  }
};
const avatarClick = () => {
  chooseMedia({ count: 1, mediaType: ["image"] }, async (resp: any) => {
    //7 创作者图片

    const url = await uploadImg(resp[0].tempFilePath, 7);
    editData.pic_url = url;
  });
};
//上传文件，添加音频----------------------------------------------------------------------------------------
// 音频效果---------------------------------------------------------------------
const LineItem1 = ref<typeof LineItem>();
const LineItem2 = ref<typeof LineItem>();
const startVoiceLine = () => {
  LineItem1.value?.getHeight();
  LineItem2.value?.getHeight();
};
const closeVoiceLine = () => {
  LineItem1.value?.close();
  LineItem2.value?.close();
};
// 音频效果---------------------------------------------------------------------
onUnmounted(() => {
  innerAudioContext.stop();
  countTimeEnd2();

  progressEnd();
  closeVoiceLine();
});
</script>

<template>
  <view class="voiceWrap">
    <view class="topItem">
      <view class="word1">录制景区</view>
      <view class="item">
        <input
          class="input1"
          v-model="editData.scenic_name"
          placeholder="请填写景区"
          placeholder-style="color: #666666"
        />
      </view>
    </view>
    <view class="topItem">
      <view class="word1">景区所在地</view>
      <view class="item" @click="areaClick">
        <text>{{ city_name ? city_name : "请选择" }}</text>
        <image src="/package/voice/static/arrow.png"></image>
      </view>
    </view>
    <view class="topItem">
      <view class="word1">讲解主题</view>
      <view class="item">
        <input
          class="input1"
          v-model="editData.title"
          placeholder="请填写主题"
          placeholder-style="color: #666666"
        />
      </view>
    </view>
    <view class="topItem">
      <view class="word1">封面</view>
      <view class="item" @click="avatarClick">
        <image
          class="info-data-img"
          :src="editData.pic_url"
          mode="aspectFill"
        />
        <image src="/package/voice/static/arrow.png"></image>
      </view>
    </view>

    <view class="topItem2">
      <view class="word1">讲解大纲</view>
      <view class="textAreaWrap">
        <textarea
          class="textArea"
          v-model="editData.desc"
          placeholder="请输入讲解大纲"
          maxlength="500"
          @input="handleInput"
        />
        <view class="wordShow">{{ inputLength }}/500</view>
      </view>
    </view>
    <view class="topItem2">
      <view class="word1">试讲内容</view>
      <view class="textAreaWrap">
        <textarea
          class="textArea"
          v-model="editData.content"
          placeholder="请输入试讲内容"
          maxlength="1000"
          @input="handleInput2"
        />
        <view class="wordShow">{{ inputLength2 }}/1000</view>
      </view>
    </view>
    <view class="topItem2">
      <view class="word1">试讲音频</view>
      <view class="voiceControl2" v-if="activeIndex == 0">
        <view class="controlItem">
          <image
            src="/package/voice/static/play.png"
            @click="startRecordVoice"
            mode="scaleToFill"
          />
          <text>点击开始录制</text>
        </view>
      </view>
      <view class="voiceControl" v-if="activeIndex == 1">
        <view class="controlTop">
          <view class="controlItem" @click="reLoadVoice">
            <image src="/package/voice/static/reload.png" mode="scaleToFill" />
            <text>重录</text>
          </view>
          <view class="controlItem controlItem2">
            <view @click="handleVoice">
              <image
                v-if="voiceState"
                src="/package/voice/static/play2.png"
                mode="scaleToFill"
              />
              <image
                v-else
                src="/package/voice/static/play.png"
                mode="scaleToFill"
              />
            </view>
            <text v-if="voiceState">点击暂停录制</text>
            <text v-else>点击继续录制</text>
          </view>
          <view class="controlItem" @click="endRecord">
            <image src="/package/voice/static/checked.png" mode="scaleToFill" />
            <text>完成录制</text>
          </view>
        </view>
        <view class="controlBottom">
          <view class="lineWrap">
            <LineItem ref="LineItem1"/>
            <view class="time">{{ dateCount.time }}</view>
            <LineItem  ref="LineItem2" />
          </view>
        </view>
      </view>
      <view class="voiceControl3" v-if="activeIndex == 2">
        <view class="controlItem" @click="reLoadVoice2">
          <image src="/package/voice/static/reload.png" mode="scaleToFill" />
          <text>重录</text>
        </view>
        <view class="bottom">
          <view @click="playVoice" class="controlItem2">
            <image
              v-if="voiceState"
              src="/package/voice/static/play2.png"
              mode="scaleToFill"
            />
            <image
              v-else
              src="/package/voice/static/play.png"
              mode="scaleToFill"
            />
          </view>
          <view class="progressWrap">
            <view class="progressParent">
              <view class="child"></view>
            </view>
            <view class="timeWrap">
              <text>{{ dateCount.time }}</text>
              <text>{{ progress.allTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
  <view class="footer">
    <view class="submit" @click="toRequire2">提交审核</view>
  </view>
  <EditAreaPicker ref="editAreaPicker" />
</template>

<style lang="scss">
page {
  padding-bottom: 0;
}
.voiceWrap {
  box-sizing: border-box;
  height: calc(100vh - 120rpx - env(safe-area-inset-bottom));
  overflow: scroll;
  background-color: #fff;
  padding: 0 30rpx 50rpx 30rpx;
  .word1 {
    width: 200rpx;
    flex-shrink: 0;
    font-size: 28rpx;

    color: #333333;
    line-height: 40rpx;
  }
  .topItem {
    box-sizing: border-box;
    height: 120rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #dddddd;

    .input1 {
      width: 100%;
    }
    .item {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width: 200rpx;
      text {
        font-size: 28rpx;
        color: #999999;
        line-height: 40rpx;
      }
      image {
        margin-left: 20rpx;
        width: 24rpx;
        height: 24rpx;
      }
    }
  }
  .topItem2 {
    .word1 {
      height: 120rpx;
      line-height: 120rpx;
    }
    .textAreaWrap {
      width: 100%;
      height: 310rpx;
      position: relative;
      .wordShow {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;
        font-size: 28rpx;

        color: #999999;
        line-height: 40rpx;
      }
    }

    .textArea {
      box-sizing: border-box;
      width: 100%;
      height: 310rpx;
      padding: 30rpx;
      background: #fbfbfb;
      border-radius: 20rpx;
    }
  }
}
.footer {
  width: 100vw;
  background: #fff;
  position: fixed;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  height: 120rpx;
  background: #ffffff;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  .submit {
    width: 630rpx;
    height: 90rpx;
    background: #ff7900;
    border-radius: 46rpx;
    text-align: center;
    font-size: 32rpx;
    color: #ffffff;
    line-height: 90rpx;
  }
}
.voiceControl {
  width: 100%;
  height: 388rpx;
  background: #fbfbfb;
  border-radius: 20rpx;
  .controlTop {
    display: flex;
    justify-content: center;
    box-sizing: border-box;
    padding-top: 68rpx;
    text {
      margin-top: 30rpx;
      font-size: 26rpx;
      color: #666666;
      line-height: 36rpx;
    }
    .controlItem {
      width: 30%;
      display: flex;
      flex-direction: column;
      align-items: center;

      image {
        width: 64rpx;
        height: 64rpx;
      }
    }
    .controlItem2 {
      image {
        width: 104rpx !important;
        height: 104rpx !important;
      }
    }
  }
  .controlBottom {
    margin-top: 40rpx;
    display: flex;
    justify-content: center;
    height: 66rpx;
    .time {
      font-size: 28rpx;
      color: #ff7b05;
      line-height: 66rpx;
    }
  }
}
.voiceControl2 {
  width: 100%;
  height: 280rpx;
  background: #fbfbfb;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .controlItem {
    display: flex;
    flex-direction: column;
    align-items: center;
    text {
      margin-top: 30rpx;
      font-size: 26rpx;
      color: #666666;
      line-height: 36rpx;
    }
    image {
      width: 104rpx !important;
      height: 104rpx !important;
    }
  }
}
.voiceControl3 {
  padding: 30rpx;
  box-sizing: border-box;
  width: 100%;
  height: 280rpx;
  background: #fbfbfb;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  .controlItem {
    display: flex;
    align-items: center;
    height: 64rpx;
    text {
      font-size: 26rpx;
      color: #666666;
      line-height: 26rpx;
    }
    image {
      margin-right: 10rpx;
      width: 64rpx;
      height: 64rpx;
    }
  }
  .controlItem2 {
    image {
      width: 104rpx !important;
      height: 104rpx !important;
    }
  }

  .bottom {
    width: 100%;
    display: flex;
    box-sizing: border-box;
    padding: 0 20rpx;
    justify-content: space-between;
    align-items: flex-end;
    .progressWrap {
      width: 462rpx;
      .progressParent {
        width: 462rpx;
        height: 10rpx;
        background-color: #ffd9c5;
        border-radius: 10rpx;
        overflow: hidden;
        .child {
          width: v-bind(width);
          height: 10rpx;
          background-color: #ff7900;
        }
      }
      .timeWrap {
        margin-top: 30rpx;
        display: flex;
        justify-content: space-between;
        text {
          font-size: 24rpx;
          color: #666666;
          line-height: 34rpx;
        }
      }
    }
  }
}
.info-data-img {
  width: 100rpx !important;
  height: 100rpx !important;
  border-radius: 10rpx;
}
.lineWrap {
  width: 300rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .time {
    margin-left: 8rpx;
    margin-right: 4rpx;
  }
}
</style>
